package com.SmartCare.schedule;

import com.SmartCare.common.enums.Constants;
import com.SmartCare.common.exception.ServiceException;
import com.SmartCare.controller.common.WXController;
import com.SmartCare.mapper.CallNoteMapper;
import com.SmartCare.mapper.role.UserMapper;
import com.SmartCare.pojo.reminder.CallNote;
import com.SmartCare.pojo.role.User;
import com.SmartCare.service.MailService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Service
@Slf4j
public class CallNoteScheduleTask {

    @Resource
    private CallNoteMapper callNoteMapper;

    @Resource
    private TaskScheduler taskScheduler;

    @Resource
    private UserMapper userMapper;

    @Resource
    private MailService mailService;

    @Resource
    private WXController wxController;

    //存储正在执行的定时任务
    private final Map<Long, ScheduledFuture<?>> scheduledTasks = new HashMap<>();


    //在spring初始化时执行，遍历数据库中的记录并添加定时任务
    @PostConstruct
    public void init() {
        scheduleTasks();
    }

    public void scheduleTasks() {
        //从数据库中获取所有的通话记录
        QueryWrapper<CallNote> qw = new QueryWrapper<>();
        //获取启用的记录
        qw.eq("status", 1);
        List<CallNote> callNotes = callNoteMapper.selectList(qw);
        if (callNotes.size() != 0) {
            //遍历通话记录并根据cron表达式动态添加定时任务
            for (CallNote callNote : callNotes) {
                //检查是否已经存在相同的任务
                if (!scheduledTasks.containsKey(callNote.getId())) {
                    //添加定时任务
                    addScheduledTask(callNote);
                }
            }
        }

    }

    //添加定时任务
    public void addScheduledTask(CallNote callNote) {
        Runnable task = () -> {
            //执行的具体逻辑
            log.info("开始执行定时任务");

            // 获取用户信息
            User user = userMapper.selectById(callNote.getFamilyMemberId());

            // 短信发送
//           SMSUtils.sendMessage("至善养老提醒您："+callNote.getReminderContent(), "SMS_154950909", user.getPhone(), "");


            // 邮件发送
            String to = user.getMail();
            if (StringUtils.isNotBlank(to)) {
                String text = "【至孝养老】通话提醒：" + callNote.getReminderContent();
                // 发送消息
                mailService.sendMsg(to, "至孝养老", text);
            } else {
                log.error("定时任务执行失败：用户[" + user.getName() + "]未绑定邮箱");
            }

            // 公众号消息发送
//            //获取用户的openId并判空
//            User user = userMapper.selectById(callNote.getFamilyMemberId());
//            if (org.apache.commons.lang3.StringUtils.isNotBlank(user.getOpenid())) {
//                //创建要发送的消息内容
//                AlarmParams alarmParams = AlarmParams.builder()
//                        .thing3(user.getName())
//                        .thing4(callNote.getReminderContent())
//                        .thing5("通话提醒")
//                        .build();
//                //发送消息
//                wxController.sendMsg(user, alarmParams);
//            } else {
//                throw new ServiceException(Constants.CODE_400, "定时任务执行出错：用户的OpenId不存在");
//            }
        };

        //根据Cron表达式调度任务
        ScheduledFuture<?> scheduledFuture = taskScheduler.schedule(task, new CronTrigger(callNote.getNotificationTime()));

        //存储任务，以便后续检查和取消
        scheduledTasks.put(callNote.getId(), scheduledFuture);
    }

    //取消指定定时任务
    public void cancelScheduledTask(Long taskId) {
        ScheduledFuture<?> scheduledFuture = scheduledTasks.get(taskId);
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledTasks.remove(taskId);
        } else {
            throw new ServiceException(Constants.CODE_400, "取消定时任务失败：未找到指定的定时任务");
        }
    }

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(10); //设置线程池大小
        taskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
        taskScheduler.initialize();
        return taskScheduler;
    }

}
